package com.to8to.kitt.esb;

import java.io.ByteArrayInputStream;
import java.util.Map;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

import com.to8to.kitt.utils.LogUtils;

public class DefaultDeamon extends AbstractDeamon{

	public String deamonFile = "deamon.properties";
//	public String zkFile = "zk.properties";
	
	@Override
	public void onPrivateConfigChange(Map<String, NodeChangeEvent> config) {
		
		String[] files = {deamonFile};
		
		for(String file: files)
		{
			NodeChangeEvent event = config.get(file);
			
			if (event == null) {
				logger.warn("can't find " + file);
				continue;
			}
			
			if(!event.isChange())
				continue;
			
			System.out.println(event);
			
			byte[] data = event.ndata;
			
			if(file.equals(deamonFile))
			{
				try {
			
					PropertiesConfiguration pc = new PropertiesConfiguration();
					
					pc.load(new ByteArrayInputStream(data));
					
					String report_host = pc.getString("report_host");
					
					super.setReportHost(report_host);
					
					super.report(true);
					
				} catch (ConfigurationException e) {
					logger.error(LogUtils.logStackTrace(e));
				}
			}
		}
	}

	@Override
	public void onCommonConfigChange(NodeChangeEvent e) {
		
		if(!e.isChange())
			return;
		
		System.out.println(e);
	}

	
	public void start(String service, String instance)
	{
		setReportAddressToZK(true);

		setSyncConfigFromZK(true);

//		ZkConfig zkconfig = new ZkConfig(zkFile);

//		setZkConfig(zkconfig);

		setServiceInstance(service, instance);

		init();
	}
	
}
